package com.dimbottom.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class H2Utils {

    private final String username;
    private final String password;
    private final String url;
    private final String driver;
    private final String prefix = "jdbc.h2.";

    private static final H2Utils instance = new H2Utils();

    private H2Utils() {
        InputStream resource = H2Utils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        try {
            properties.load(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        username = properties.getProperty(prefix + "username");
        password = properties.getProperty(prefix + "password");
        url = properties.getProperty(prefix + "url");
        driver = properties.getProperty(prefix + "driver");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static H2Utils getInstance() {
        return instance;
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(instance.url, instance.username, instance.password);
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (connection != null)
                connection.close();
            if (statement != null)
                statement.close();
            if (resultSet != null)
                resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
